import React, {useEffect, useState} from 'react';
import {Building2, ChevronDown, ChevronRight, X} from 'lucide-react';
import {Req} from "../../util/fetch.ts";

interface User {
    id: number;
    realname: string;
    avatarUrl: string;
    position: string;
}

interface UserManageModalProps {
    mode: 'add' | 'edit';
    training: any;
    onClose: () => void;
    onSave: (users: User[]) => void;
}

// Mock data
// const mockUsers: User[] = [
//     {
//         id: 1,
//         realname: '张三',
//         avatarUrl: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e',
//         position: '销售部'
//     },
//     {
//         id: 2,
//         realname: '李四',
//         avatarUrl: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330',
//         position: '市场部'
//     }
// ];

// const mockDepartments = [
//     {
//         id: 1,
//         name: '华东区',
//         children: [
//             {
//                 id: 11,
//                 name: '上海团队',
//                 children: [
//                     {
//                         id: 111,
//                         name: '销售部',
//                         users: mockUsers
//                     },
//                     {
//                         id: 112,
//                         name: '市场部',
//                         users: mockUsers
//                     }
//                 ]
//             }
//         ]
//     }
// ];

export default function UserManageModal({
                                            training,
                                            onClose,
                                            onSave
                                        }: UserManageModalProps) {
    const [selectedUsers, setSelectedUsers] = useState<User[]>([]);
    const [expandedDepts, setExpandedDepts] = useState<number[]>([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [treeList, setTreeList] = useState([]);

    const toggleDepartment = (deptId: number) => {
        setExpandedDepts(prev =>
            prev.includes(deptId)
                ? prev.filter(id => id !== deptId)
                : [...prev, deptId]
        );
    };

    const toggleUser = (user: User) => {
        setSelectedUsers(prev =>
            prev.some(u => u.id === user.id)
                ? prev.filter(u => u.id !== user.id)
                : [...prev, user]
        );
    };

    const handleSubmit = () => {
        const list = []
        selectedUsers.forEach(user => list.push({trainId: training.id, personId: user.id}))
        onSave(list);
    };

    const queryAreaTree = async () => {
        const res = await Req('/bsArea/tree');
        setTreeList(res.data);
    }

    useEffect(() => {
        queryAreaTree()
        setSelectedUsers(training.personList)
    }, []);

    // Recursive function to render department tree
    const renderDepartment = (dept: any, level = 0) => {
        const isExpanded = expandedDepts.includes(dept.id);

        return (
            <div key={dept.id} className="select-none">
                <div
                    className={`flex items-center py-2 px-3 rounded-lg hover:bg-gray-50
            ${level > 0 ? 'ml-6' : ''}`}
                >
                    {(dept.children?.length || dept.users?.length) > 0 && (
                        <button
                            onClick={() => toggleDepartment(dept.id)}
                            className="p-1 hover:bg-gray-200 rounded"
                        >
                            {isExpanded ? (
                                <ChevronDown className="w-4 h-4 text-gray-500"/>
                            ) : (
                                <ChevronRight className="w-4 h-4 text-gray-500"/>
                            )}
                        </button>
                    )}

                    <div className="flex items-center flex-1">
                        <Building2 className="w-5 h-5 mr-2 text-gray-400"/>
                        <span className="font-medium">{dept.name}</span>
                    </div>
                </div>

                {isExpanded && (
                    <div>
                        {dept.children?.map((child: any) => renderDepartment(child, level + 1))}
                        {dept.users?.map((user: User) => (
                            <div
                                key={user.id}
                                className={`flex items-center py-2 px-3 ml-6 rounded-lg hover:bg-gray-50`}
                            >
                                <input
                                    type="checkbox"
                                    checked={selectedUsers.some(u => u.id === user.id)}
                                    onChange={() => toggleUser(user)}
                                    className="w-4 h-4 mr-3 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                />
                                <img
                                    src={user.avatarUrl}
                                    className="w-8 h-8 rounded-full mr-2"
                                />
                                <div>
                                    <div className="font-medium text-gray-900">
                                        {user.realname}
                                    </div>
                                    <div className="text-sm text-gray-500">
                                        {user.position}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
            <div className="bg-white rounded-lg w-full max-w-4xl mx-4 max-h-[90vh] flex flex-col">
                <div className="flex items-center justify-between p-4 border-b">
                    <h3 className="text-lg font-semibold text-gray-900">人员管理</h3>
                    <button onClick={onClose}>
                        <X className="w-6 h-6 text-gray-500"/>
                    </button>
                </div>

                <div className="p-4 border-b">
                    <input
                        type="text"
                        placeholder="搜索用户..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                </div>

                <div className="flex-1 flex overflow-hidden">
                    {/* Left: Department Tree */}
                    <div className="w-1/2 border-r overflow-y-auto p-4">
                        {treeList.map(dept => renderDepartment(dept))}
                    </div>

                    {/* Right: Selected Users */}
                    <div className="w-1/2 overflow-y-auto p-4">
                        <div className="mb-4">
                            <h4 className="text-lg font-medium text-gray-900">
                                已选择人员 ({selectedUsers.length})
                            </h4>
                        </div>
                        <div className="space-y-2">
                            {selectedUsers.map(user => (
                                <div
                                    key={user.id}
                                    className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                                >
                                    <div className="flex items-center">
                                        <img
                                            src={user.avatarUrl}
                                            className="w-8 h-8 rounded-full mr-3"
                                        />
                                        <div>
                                            <div className="font-medium text-gray-900">
                                                {user.realname}
                                            </div>
                                            <div className="text-sm text-gray-500">
                                                {user.position}
                                            </div>
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => toggleUser(user)}
                                        className="p-1 text-gray-400 hover:text-red-500"
                                    >
                                        <X className="w-5 h-5"/>
                                    </button>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>

                <div className="flex justify-between items-center p-4 bg-gray-50 rounded-b-lg">
                    <div className="text-sm text-gray-600">
                        已选择 {selectedUsers.length} 人
                    </div>
                    <div className="space-x-3">
                        <button
                            onClick={onClose}
                            className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
                        >
                            取消
                        </button>
                        <button
                            onClick={handleSubmit}
                            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                        >
                            确定
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}